package com.duowei.diandan.sql;

import android.os.Handler;
import android.support.annotation.WorkerThread;
import android.text.TextUtils;
import android.util.Log;

import com.duowei.diandan.app.OrderList;
import com.duowei.diandan.app.SqlServerDateTime;
import com.duowei.diandan.bean.CouponDealRecord;
import com.duowei.diandan.bean.Czkjymxxx;
import com.duowei.diandan.bean.DealRecord;
import com.duowei.diandan.bean.ImsCardDealRecord;
import com.duowei.diandan.bean.ImsCardJfRecord;
import com.duowei.diandan.bean.ImsCardMembers;
import com.duowei.diandan.bean.ImsCardMembersCoupon;
import com.duowei.diandan.bean.ImsJfgzsz;
import com.duowei.diandan.bean.Money;
import com.duowei.diandan.bean.Payment;
import com.duowei.diandan.bean.Pbdyxxb;
import com.duowei.diandan.bean.QrCodePay;
import com.duowei.diandan.bean.UserCardInfo;
import com.duowei.diandan.constant.ChoiceType;
import com.duowei.diandan.constant.NetConfig;
import com.duowei.diandan.constant.PayType;
import com.duowei.diandan.constant.PlateMode;
import com.duowei.diandan.constant.PrintMode;
import com.duowei.diandan.constant.Settings;
import com.duowei.diandan.db.AppDatabase;
import com.duowei.diandan.db.entry.Jgsz;
import com.duowei.diandan.db.entry.Wmlsb;
import com.duowei.diandan.db.entry.Wmlsbjb;
import com.duowei.diandan.db.entry.Wxfwqdz;
import com.duowei.diandan.event.ToastEvent;
import com.duowei.diandan.print.PayTicketPrintDataMaker;
import com.duowei.diandan.print2.InsidePrint;
import com.duowei.diandan.print3.Print3;
import com.duowei.diandan.util.NetUtils;

import org.greenrobot.eventbus.EventBus;
import org.joda.time.LocalDateTime;

import java.io.IOException;
import java.util.List;

import am.util.printer.PrintExecutor;
import am.util.printer.PrinterWriter80mm;

/**
 * 快餐模式数据提交
 */
public class DataCommit {
    private static final String TAG = "DataCommit";

    private Handler mHandler = new Handler();

    private AppDatabase mDb = AppDatabase.getDatabase();
    private Wmlsbjb mWmlsbjb;
    private List<Wmlsb> mWmlsbList;

    private boolean mRemoteCommit;
    private Money mMoney;

    private LocalDateTime mCurrentDatetime;
    private String mCurrentDatetimeStr;
    private int mLocalPrk;
    private Float mPayMoney = 0f;

    private String mDealId;
    private String mPlateNo;

    private float mXsjbxxHyjf = 0; // 本次获得积分

    private OnCommitListener mOnCommitListener;

    private Thread mThread;

    public DataCommit(OnCommitListener onCommitListener) {
        mOnCommitListener = onCommitListener;
    }

    private void handleWmlsbjbAndWmlsb() {
        mWmlsbjb = mDb.wmlsbjbDao().findOne();
        mWmlsbList = mDb.wmlsbDao().findAll();

        boolean takeOut = Settings.CHOICE_TYPE == ChoiceType.TAKE_OUT;
        for (Wmlsb w : mWmlsbList) {
            w.setWmdbh(mWmlsbjb.getWmdbh());
            w.setSyyxm(Settings.DEFAULT_YHJBQK.getYhmc());
            w.setSfyxd("1");

            if (takeOut) {
                if (TextUtils.isEmpty(w.getPz())) {
                    w.setPz("(打包)");
                } else {
                    w.setPz(w.getPz() + "(打包)");
                }
            }

            mDb.wmlsbDao().update(w);
        }

        if (mRemoteCommit) {
            mWmlsbjb.setYsje(mMoney.getTotalFloat());
            mWmlsbjb.setYs(mMoney.getReceivableFloat());
            mWmlsbjb.setSs(mMoney.getReceivableFloat());
            mWmlsbjb.setZk(mMoney.getDiscountFloat());
        } else {
            mWmlsbjb.setYs(mMoney.getTotalFloat());
        }

        // --
        mWmlsbjb.setZh(mPlateNo);
        mWmlsbjb.setJcfs(Settings.CHOICE_TYPE.toString());

        mDb.wmlsbjbDao().update(mWmlsbjb);
    }

    /**
     * 付款结账
     */
    public void dataCommit(boolean remoteCommit) {
        mRemoteCommit = remoteCommit;
        mMoney = OrderList.getInstance().getMoney();

        if (mRemoteCommit) {
            // 付款提交数据
            mThread = new Thread(() -> {
                mCurrentDatetime = SqlServerDateTime.getInstance().getNowServerDateTime();
                mCurrentDatetimeStr = mCurrentDatetime.toString("yyyy-MM-dd HH:mm:ss");

                //
                while (true) {
                    if (Thread.currentThread().isInterrupted()) {
                        return;
                    }

                    try {
                        httpGetPrk();
                        break;
                    } catch (IOException e) {
                        Log.e(TAG, "", e);

                        EventBus.getDefault().post(new ToastEvent("获取PRK失败,重新获取,请等待", false));

                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException e1) {
                            Thread.currentThread().interrupt();
                        }
                    }
                }

                //
                boolean result = handlePlateModeOfAuto();
                if (!result) {
                    if (mOnCommitListener != null) {
                        mHandler.post(() -> mOnCommitListener.onPlateNotSet());
                    }
                    return;
                }

                handleWmlsbjbAndWmlsb();

                //
                while (true) {
                    if (Thread.currentThread().isInterrupted()) {
                        return;
                    }

                    try {
                        httpPostDataToMySql();
                        break;
                    } catch (IOException e) {
                        Log.e(TAG, "", e);

                        EventBus.getDefault().post(new ToastEvent("提交数据给远程服务器失败,重新提交,请等待", false));

                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException e1) {
                            Thread.currentThread().interrupt();
                        }
                    }
                }

                while (true) {
                    if (Thread.currentThread().isInterrupted()) {
                        return;
                    }

                    try {
                        httpPostDataToSqlServer();
                        break;
                    } catch (IOException e) {
                        Log.e(TAG, "", e);

                        EventBus.getDefault().post(new ToastEvent("提交数据给本地服务器失败,重新提交,请等待", false));

                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException e1) {
                            Thread.currentThread().interrupt();
                        }
                    }
                }

                print(false);

                if (mOnCommitListener != null) {
                    mHandler.post(() -> mOnCommitListener.onSuccess());
                }

            });
            mThread.start();

        } else {
            // 前台结算
            mThread = new Thread(() -> {
                //
                while (true) {
                    if (Thread.currentThread().isInterrupted()) {
                        return;
                    }

                    try {
                        httpGetPrk();
                        break;
                    } catch (IOException e) {
                        Log.e(TAG, "", e);

                        EventBus.getDefault().post(new ToastEvent("获取PRK失败,重新获取,请等待", false));

                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException e1) {
                            Thread.currentThread().interrupt();
                        }
                    }
                }

                //
                boolean result = handlePlateModeOfAuto();
                if (!result) {
                    if (mOnCommitListener != null) {
                        mHandler.post(() -> mOnCommitListener.onPlateNotSet());
                    }
                    return;
                }

                handleWmlsbjbAndWmlsb();

                //
                StringBuilder sql = new StringBuilder(SqlHelper.toInsertSql(mWmlsbjb));
                for (Wmlsb w : mWmlsbList) {
                    sql.append(SqlHelper.toInsertSql(w));
                }

                // 平板打印
                String insertPbdyxxb = Pbdyxxb.toInsertString(
                        mWmlsbjb.getWmdbh(),
                        mPlateNo,
                        Settings.DEVICE_NAME,
                        String.valueOf(1)
                );
                sql.append(insertPbdyxxb);

                //
                while (true) {
                    if (Thread.currentThread().isInterrupted()) {
                        return;
                    }

                    try {
                        NetUtils.post7(NetConfig.getServerUrl(), sql.toString());
                        break;
                    } catch (IOException e) {
                        Log.e(TAG, "", e);

                        EventBus.getDefault().post(new ToastEvent("提交数据给本地服务器失败,重新提交,请等待", false));

                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException e1) {
                            Thread.currentThread().interrupt();
                        }
                    }
                }

                //
                print(true);

                if (mOnCommitListener != null) {
                    mHandler.post(() -> mOnCommitListener.onSuccess());
                }
            });
            mThread.start();
        }
    }

    public void stopCommit() {
        if (mThread != null && mThread.isAlive()) {
            mThread.interrupt();
        }
    }

    /**
     * 获取sql server prk
     * <p>
     * // [ { "prk":"2" }]
     */
    @WorkerThread
    private void httpGetPrk() throws IOException {
        String sql = Prk.querySql("WMLSBJB" + SqlServerDateTime.getInstance().getyyyyMMddStr());
        List<Prk> prkList = NetUtils.post6(NetConfig.getServerUrl(), sql, Prk.class);
        if (prkList.size() > 0) {
            mLocalPrk = Integer.valueOf(prkList.get(0).prk);
        }
    }

    /**
     * 餐牌模式 自动模式 处理
     */
    private boolean handlePlateModeOfAuto() {
        if (PlateMode.AUTO == Settings.PLATE_MODE) {
            Jgsz jgsz = mDb.jgszDao().findOne();
            if (jgsz != null && jgsz.getBy14() != null && jgsz.getBy66() != null) {
                mPlateNo = String.valueOf((mLocalPrk % (jgsz.getBy14() + 1 - jgsz.getBy66())) + jgsz.getBy66());
            } else {
                return false;
            }
        } else {
            mPlateNo = Settings.PLATE_NO;
        }

        return true;
    }

    @WorkerThread
    private void httpPostDataToMySql() throws IOException {
        // 是否需要上传到 mysql
        int flag = 0; // 0 不处理; 1 只有云会员支付; 2 只有微信、支付宝支付; 3 云会员、微信、支付宝支付

        List<Payment> paymentList = OrderList.getInstance().getPaymentList(); // 付款方式
        QrCodePay qrCodePay = OrderList.getInstance().getQrCodePay();

        if ((paymentList == null || paymentList.size() == 0)) {
            if (qrCodePay == null) {
                flag = 0;
            } else if (OrderList.getInstance().isCloudQrCode()) {
                flag = 2;
            } else {
                flag = 0;
            }
        } else {
            // paymentList != null && paymentList.size() > 0
            if (qrCodePay == null) {
                flag = 1;
            } else {
                // qrCodePay != null
                if (OrderList.getInstance().isCloudQrCode()) {
                    flag = 3;
                } else {
                    flag = 1;
                }
            }
        }

        // ------------------------------------------------
        String remoteSql = ""; // 汇总sql
        float paymentMoney = 0.0f; //储值消费的金额
        float cash = 0.0f; // 现金
        UserCardInfo cardInfo = OrderList.getInstance().getUserCardInfo();
        String syjh = Settings.DEVICE_NAME;
        String yhmc = Settings.DEFAULT_YHJBQK.getYhmc();

        Wxfwqdz wxfwqdz = mDb.wxfwqdzDao().findOne();

        if (flag == 1 || flag == 2 || flag == 3) {
            // 获取MySql dealId
            List<MysqlTableKey> mysqlTableKeyList = NetUtils.post6(NetConfig.getWeiXinServerUrl(wxfwqdz.getAndroidSip()), MysqlTableKey.querySql(), MysqlTableKey.class);
            mDealId = mysqlTableKeyList.get(0).table_key;

            // 获取MySql 积分规则
            List<ImsJfgzsz> imsJfgzszList = NetUtils.post6(NetConfig.getWeiXinServerUrl(wxfwqdz.getAndroidSip()), ImsJfgzsz.toSelectString(wxfwqdz.getWeid()), ImsJfgzsz.class);
            ImsJfgzsz imsJfgzsz = imsJfgzszList.get(0);

            if (flag == 1 || flag == 3) {
                // 付款方式及付款明细处理
                //noinspection ConstantConditions
                for (int i = 0; i < paymentList.size(); i++) {
                    Payment payment = paymentList.get(i);
                    PayType payType = payment.payType;
                    if (payType == PayType.STORED_VALUE_TYPE) {
                        // 储值消费处理

                        // 更新卡余额
                        String updateImsCardMembers = ImsCardMembers.toUpdateCredit2String(Integer.valueOf(wxfwqdz.getWeid()), cardInfo.getFromUser(), cardInfo.getCredit2() - payment.payMoney);

                        // 插入记录 会员卡充值消费明细 ims_card_deal_record
                        ImsCardDealRecord imsCardDealRecord = new ImsCardDealRecord();
                        imsCardDealRecord.setWeid(Integer.valueOf(wxfwqdz.getWeid()));
                        imsCardDealRecord.setFromUser(cardInfo.getFromUser());
                        imsCardDealRecord.setJysj(mCurrentDatetime);
                        imsCardDealRecord.setCzqje(cardInfo.getCredit2());
                        imsCardDealRecord.setKczje(-payment.payMoney);
                        imsCardDealRecord.setSyjh(Settings.DEVICE_NAME);
                        imsCardDealRecord.setYhmc(yhmc);
                        imsCardDealRecord.setBmbh(wxfwqdz.getBmbh());
                        imsCardDealRecord.setDealId(mDealId);
                        imsCardDealRecord.setKye(imsCardDealRecord.getCzqje() + imsCardDealRecord.getKczje());
                        imsCardDealRecord.setJylx("储值卡消费");

                        // 汇总sql
                        remoteSql += updateImsCardMembers + SqlHelper.toInsertSql(imsCardDealRecord);

                        mPayMoney += payment.payMoney;

                        // 记录消费的金额
                        paymentMoney += payment.payMoney;

                        // 积分规则处理 - 按消费金额获取积分
                        if (imsJfgzsz != null && imsJfgzsz.jfly == 0) {
                            // 2 储值卡消费
                            // 3 现金消费和储值卡消费金额
                            if (imsJfgzsz.jfgz == 2 || imsJfgzsz.jfgz == 3) {
                                mXsjbxxHyjf += payment.payMoney * imsJfgzsz.jfbfb / 100.0f; // 操作积分
                            }
                        }

                    } else if (payType == PayType.INTEGRAL_TYPE) {
                        // 积分消费处理

                        // 更新积分
                        String updateImsCArdMembers = ImsCardMembers.toUpdateCredit1String(Integer.valueOf(wxfwqdz.getWeid()), cardInfo.getFromUser(), cardInfo.getCredit1() - payment.jfValue);

                        // 插入 会员积分交易记录 ims_card_jf_record
                        ImsCardJfRecord imsCardJfRecord = new ImsCardJfRecord();
                        imsCardJfRecord.setWeid(Integer.valueOf(wxfwqdz.getWeid()));
                        imsCardJfRecord.setFromUser(cardInfo.getFromUser());
                        imsCardJfRecord.setJysj(mCurrentDatetime);
                        imsCardJfRecord.setJylx("积分消费");
                        imsCardJfRecord.setCzqjf(cardInfo.getCredit1());
                        imsCardJfRecord.setKczjf(-payment.jfValue);
                        imsCardJfRecord.setSyjf(cardInfo.getCredit1() - payment.jfValue);
                        imsCardJfRecord.setSyjh(Settings.DEVICE_NAME);
                        imsCardJfRecord.setYhmc(yhmc);
                        imsCardJfRecord.setDealId(mDealId);
                        imsCardJfRecord.setBmbh(wxfwqdz.getBmbh());
                        imsCardJfRecord.setUid(cardInfo.getUid());

                        // 汇总sql
                        remoteSql += updateImsCArdMembers + SqlHelper.toInsertSql(imsCardJfRecord);
                    } else if (payType == PayType.COUPON_TYPE) {
                        // 券消费处理

                        // 更新券使用状态
                        String updateImsCArdMembersCoupon = ImsCardMembersCoupon.toUpdateString(
                                Integer.valueOf(wxfwqdz.getWeid()),
                                cardInfo.getFromUser(),
                                Integer.valueOf(payment.id),
                                yhmc,
                                mCurrentDatetimeStr,
                                mDealId,
                                payment.ticketNum
                        );

                        // 插入记录
                        CouponDealRecord couponDealRecord = new CouponDealRecord();
                        couponDealRecord.setWeid(Integer.valueOf(wxfwqdz.getWeid()));
                        couponDealRecord.setFromUser(cardInfo.getFromUser());
                        couponDealRecord.setCouponid(Integer.valueOf(payment.id));
                        couponDealRecord.setJysj(mCurrentDatetime);
                        couponDealRecord.setSl(-payment.ticketNum);
                        couponDealRecord.setSyjh(Settings.DEVICE_NAME);
                        couponDealRecord.setYhmc(yhmc);
                        couponDealRecord.setDealId(mDealId);
                        couponDealRecord.setBmbh(wxfwqdz.getBmbh());
                        couponDealRecord.setTitle(payment.title);
                        couponDealRecord.setJyje(-payment.payMoney);
                        couponDealRecord.setBz(payment.title + "(" + payment.ticketNum + "张)");
                        couponDealRecord.setUid(cardInfo.getUid());
                        couponDealRecord.setJylx("券消费");

                        remoteSql += updateImsCArdMembersCoupon + SqlHelper.toInsertSql(couponDealRecord);
                    }
                } // for end
            } // if end

            if (flag == 2 || flag == 3) {
                // 有微信、支付宝的DealRecord数据要上传,现金处理
                cash = qrCodePay.getPrice();

                // 积分规则处理
                if (imsJfgzsz != null && imsJfgzsz.jfly == 0) {
                    if (imsJfgzsz.jfgz == 1 || imsJfgzsz.jfgz == 3) {
                        mXsjbxxHyjf += cash * imsJfgzsz.jfbfb / 100.0f; // 操作积分
                    }
                }
            }

            // 插入 消费明细表 (只插入一次)
            DealRecord dealRecord = new DealRecord();
            dealRecord.setWeid(Integer.valueOf(wxfwqdz.getWeid()));
            dealRecord.setFromUser(cardInfo.getFromUser());
            dealRecord.setJysj(mCurrentDatetime);
            dealRecord.setSyjh(syjh);
            dealRecord.setYhmc(yhmc);
            dealRecord.setBmbh(wxfwqdz.getBmbh());
            dealRecord.setDealId(mDealId);
            dealRecord.setCash(cash); // 现金
            dealRecord.setJezj(mMoney.getReceivableFloat()); // 应收金额
            dealRecord.setPayment1(paymentMoney); // 储值卡支付金额
            dealRecord.setXsdh(mWmlsbjb.getWmdbh() + "_" + wxfwqdz.getBmbh());
            dealRecord.setJylx("消费");
            dealRecord.setUid(cardInfo.getUid());

            remoteSql += SqlHelper.toInsertSql(dealRecord);

            // --------------------------------------------------------

            //获取积分处理
            if (mXsjbxxHyjf > 0) {
                ImsCardJfRecord imsCardJfRecord = new ImsCardJfRecord();
                imsCardJfRecord.setWeid(Integer.valueOf(wxfwqdz.getWeid()));
                imsCardJfRecord.setFromUser(cardInfo.getFromUser());
                imsCardJfRecord.setJysj(mCurrentDatetime);
                imsCardJfRecord.setJylx("获取积分");
                imsCardJfRecord.setCzqjf(cardInfo.getCredit1());
                imsCardJfRecord.setKczjf(mXsjbxxHyjf);
                imsCardJfRecord.setSyjf(cardInfo.getCredit1() + mXsjbxxHyjf);
                imsCardJfRecord.setSyjh(Settings.DEVICE_NAME);
                imsCardJfRecord.setYhmc(yhmc);
                imsCardJfRecord.setDealId(mDealId);
                imsCardJfRecord.setBmbh(wxfwqdz.getBmbh());
                imsCardJfRecord.setUid(cardInfo.getUid());

                // 更新积分
                String updateImsCArdMembers = ImsCardMembers.toUpdateCredit1String(Integer.valueOf(wxfwqdz.getWeid()), cardInfo.getFromUser(), cardInfo.getCredit1() + mXsjbxxHyjf);
                remoteSql += SqlHelper.toInsertSql(imsCardJfRecord) + updateImsCArdMembers;
            }
        }

        // 提交数据给 mysql
        if (!TextUtils.isEmpty(remoteSql)) {
            NetUtils.post7(NetConfig.getWeiXinServerUrl(wxfwqdz.getAndroidSip()), remoteSql);
        }
    }

    @WorkerThread
    private void httpPostDataToSqlServer() throws IOException {
        StringBuilder sql = new StringBuilder();

        // Wmlsbjb
        if (mDealId != null) {
            mWmlsbjb.setJzbz(mDealId);
        }
        UserCardInfo cardInfo = OrderList.getInstance().getUserCardInfo();
        if (cardInfo != null) {
            mWmlsbjb.setBy8(cardInfo.getFromUser());
            mWmlsbjb.setHykh(cardInfo.getCardsn());
        }

        sql.append(SqlHelper.toInsertSql(mWmlsbjb));

        // Wmlsb
        for (Wmlsb w : mWmlsbList) {
            sql.append(SqlHelper.toInsertSql(w));
        }

        // 平板打印
        String insertPbdyxxb = Pbdyxxb.toInsertString(
                mWmlsbjb.getWmdbh(),
                mPlateNo,
                Settings.DEVICE_NAME,
                "1"
        );
        sql.append(insertPbdyxxb);


        // ---------------------------- start
        String wmdbh = mWmlsbjb.getWmdbh();
        String yhbh = Settings.DEFAULT_YHJBQK.getYhbh();
        String yhmc = Settings.DEFAULT_YHJBQK.getYhmc();

        //消费基本信息表XSJBXX
        Xsjbxx xsjbxx = new Xsjbxx();
        xsjbxx.setXsdh(mWmlsbjb.getWmdbh());
        xsjbxx.setXh(yhbh);
        xsjbxx.setDdybh(yhmc);
        xsjbxx.setZs("无折扣");
        xsjbxx.setJezj(mMoney.getTotalFloat());
        xsjbxx.setZkje(mMoney.getDiscountFloat());
        xsjbxx.setZrje(0f);
        xsjbxx.setYs(mMoney.getReceivableFloat());
        xsjbxx.setSs(0f);
        xsjbxx.setDdsj(mCurrentDatetime);
        xsjbxx.setJysj(mCurrentDatetime);
        xsjbxx.setBz(Settings.DEVICE_NAME);
        xsjbxx.setJzfsbm(Settings.CHOICE_TYPE.toString());
        xsjbxx.setBmmc(null);
        xsjbxx.setWmbs(mLocalPrk);
        xsjbxx.setZh(mPlateNo);
        xsjbxx.setKhbh("0"); // 收现
        xsjbxx.setQkje(0f);
        xsjbxx.setJcrs(1);
        xsjbxx.setBy7(null); // 结账备注
        xsjbxx.setCxyh(mWmlsbjb.getBy13()); // 微信支付或支付宝支付单号
        xsjbxx.setHyjf(mXsjbxxHyjf); // 本次获得积分

        if (cardInfo != null) {
            xsjbxx.setHybh(cardInfo.getCardsn()); // 会员卡号
            xsjbxx.setCzkye(cardInfo.getCredit2() - mPayMoney); // 储值卡余额
        }

        sql.append(SqlHelper.toInsertSql(xsjbxx));

        // 消费明细表XSMXXX
        String insertXSMXXX = "insert into XSMXXX(XH,XSDH,xmbh,xmmc,TM,dw,YSJG,XSJG,SL,XSJEXJ,FTJE,SYYXM,SQRXM,SFXS,ZSSJ,TCXMBH,SSLBBM,BZ)" +
                "select wmdbh+convert(varchar(10),xh),wmdbh,xmbh,xmmc,tm,dw,ysjg,dj,sl,ysjg*sl,dj*sl,syyxm,SQRXM,SFXS,ZSSJ,TCXMBH,by2,BY13 from wmlsb where wmdbh='" + wmdbh + "'|";
        sql.append(insertXSMXXX);


        // 销售付款方式XSFKFS 注:几种付款方式就插几次
        final List<Payment> paymentList = OrderList.getInstance().getPaymentList(); // 付款方式
        if (paymentList == null || paymentList.size() == 0) {
            Log.i(TAG, "dataCommitOfCheckout: 没有选择的付款方式!");
        } else {
            for (int i = 0; i < paymentList.size(); i++) {
                Payment payment = paymentList.get(i);
                PayType payType = payment.payType;
                if (payType == PayType.STORED_VALUE_TYPE) {
                    // 储值消费
                    Xsfkfs xsfkfs = new Xsfkfs();
                    xsfkfs.setXsdh(mWmlsbjb.getWmdbh());
                    xsfkfs.setBm("999999999");
                    xsfkfs.setNr(payment.title);
                    xsfkfs.setFkje(payment.payMoney);
                    xsfkfs.setDyqzs(0);

                    sql.append(SqlHelper.toInsertSql(xsfkfs));
                } else if (payType == PayType.INTEGRAL_TYPE) {
                    // 积分消费
                    Xsfkfs xsfkfs = new Xsfkfs();
                    xsfkfs.setXsdh(mWmlsbjb.getWmdbh());
                    xsfkfs.setBm("999999998");
                    xsfkfs.setNr(payment.title);
                    xsfkfs.setFkje(payment.payMoney);
                    xsfkfs.setDyqzs(0);

                    sql.append(SqlHelper.toInsertSql(xsfkfs));
                } else if (payType == PayType.COUPON_TYPE) {
                    // 券消费
                    Xsfkfs xsfkfs = new Xsfkfs();
                    xsfkfs.setXsdh(mWmlsbjb.getWmdbh());
                    xsfkfs.setBm(payment.id);
                    xsfkfs.setNr(payment.title);
                    xsfkfs.setFkje(payment.payMoney);
                    xsfkfs.setDyqzs(payment.ticketNum);

                    sql.append(SqlHelper.toInsertSql(xsfkfs));
                }
            }

        }

        // 微信或支付宝 销售付款方式XSFKFS 处理
        QrCodePay qrCodePay = OrderList.getInstance().getQrCodePay();
        if (!TextUtils.isEmpty(mWmlsbjb.getBy13())) {
            if (TextUtils.isEmpty(mWmlsbjb.getBy16())) {
                //微信
                Xsfkfs xsfkfs = new Xsfkfs();
                xsfkfs.setXsdh(mWmlsbjb.getWmdbh());
                xsfkfs.setBm("WWWWW");
                xsfkfs.setNr("微信支付");
//                xsfkfs.setFkje(mMoney.getUnpaidFloat());
                xsfkfs.setFkje(qrCodePay != null ? qrCodePay.getPrice() : null);
                xsfkfs.setDyqzs(0);

                sql.append(SqlHelper.toInsertSql(xsfkfs));
            } else {
                //支付宝
                Xsfkfs xsfkfs = new Xsfkfs();
                xsfkfs.setXsdh(mWmlsbjb.getWmdbh());
                xsfkfs.setBm("PPPPP");
                xsfkfs.setNr("支付宝支付");
                xsfkfs.setFkje(qrCodePay != null ? qrCodePay.getPrice() : null);
                xsfkfs.setDyqzs(0);

                sql.append(SqlHelper.toInsertSql(xsfkfs));
            }
        }

        //
        if (cardInfo != null && mPayMoney != null && mPayMoney > 0) {
            Czkjymxxx czkjymxxx = new Czkjymxxx(
                    cardInfo.getCardsn(),
                    cardInfo.getCredit2(),
                    mPayMoney,
                    Settings.DEVICE_NAME,
                    Settings.DEFAULT_YHJBQK.getYhmc());
            sql.append(czkjymxxx.toInsertString());
        }

        String updateWMLSBJB = "update WMLSBJB set JSJ='" + Settings.DEVICE_NAME + "',SFYJZ='1',DJLSH='" + mLocalPrk + "',BY13=" + mWmlsbjb.getBy13() + ",BY16=" + mWmlsbjb.getBy16() + ",JSKSSJ=getdate() where wmdbh='" + wmdbh + "'|";
        sql.append(updateWMLSBJB);

        // 启动清台功能，让桌子占用
//        String showTableSql = "INSERT INTO JCZTB (csbh, jcsj, ys, zh, jcrs, wmdbh, by5) VALUES ('" + mDesk.CSBH + "', getdate(), null, '" + mDesk.CSMC + ",', " + 1 + ", '" + wmdbh + "', null)|";
        String showTableSql = "INSERT INTO JCZTB (csbh, jcsj, ys, zh, jcrs, wmdbh, by5) VALUES (null, getdate(), null, '" + mPlateNo + ",', " + 1 + ", '" + wmdbh + "', null)|";
        sql.append(showTableSql);

        // 提交数据给sql server
        NetUtils.post7(NetConfig.getServerUrl(), sql.toString());
    }

    /**
     * 打印小票
     */
    private void print(boolean isCommit) {
        if (Settings.PRINTER_MODE == PrintMode.INSIDE_MODE) {
            new InsidePrint(mHandler).print(mWmlsbjb, mWmlsbList, isCommit);

        } else if (Settings.PRINTER_MODE == PrintMode.INSIDE_MODE_GUANG_ZHOU) {
            if (Print3.getInstance().isConnected()) {
                Print3.getInstance().print(mWmlsbjb, mWmlsbList, isCommit);
            } else {
                Print3.getInstance().connect(() -> Print3.getInstance().print(mWmlsbjb, mWmlsbList, isCommit));
            }
        }

        // 外置打印
        if (Settings.PRINTER_IP_ENABLE && !TextUtils.isEmpty(Settings.PRINTER_IP)) {
            String[] ips = Settings.PRINTER_IP.split("[;；]");
            for (String ip : ips) {
                new PrintExecutor(ip, 9100, PrinterWriter80mm.TYPE_80)
                        .doPrinterRequestAsync(new PayTicketPrintDataMaker(mWmlsbjb, mWmlsbList, isCommit));
            }
        }
    }

    public interface OnCommitListener {
        void onSuccess();

        void onPlateNotSet();
    }
}
